﻿using AutoMapper;
using B.S.Backtrack.Domain.Entities;
using B.S.Backtrack.ErrorCode;
using B.S.Backtrack.Infrastructure.Interface;
using B.S.Backtrack.Write.API.Application.Command.Firms;
using MediatR;

namespace B.S.Backtrack.Write.API.Application.CommandHandler.Firms
{
    public class CreateProcesFileHandler : IRequestHandler<CreateProcesFileCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Firm> fiRep;
        private readonly IMapper mapper;

        public CreateProcesFileHandler(IBaseRepository<Firm> fiRep,IMapper mapper)
        {
            this.fiRep = fiRep;
            this.mapper = mapper;
        }
        public Task<ApiResult<int>> Handle(CreateProcesFileCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> result = new ApiResult<int>();
            // 查找或创建记录
            var firm = fiRep
                .GetAll().FirstOrDefault(f => f.ProductId == request.ProductId && !f.IsDel);

            if (firm == null)
            {
                firm = new Firm { ProductId = request.ProductId };
                fiRep.Add(firm);
                result.Code = ApiEnums.添加成功;
                result.Msg = ApiEnums.添加成功.ToString();
                result.Data = 1;
            }
            else
            {
                // 更新屠宰字段
                firm.ProcessingCompanyName = request.ProcessingCompanyName;
                firm.ProductionNum = request.ProductionNum;
              
                fiRep.Update(firm);
                result.Code = ApiEnums.修改成功;
                result.Msg = ApiEnums.修改成功.ToString();
                result.Data = 1;
            }



            return Task.FromResult(result);
        }
    }
}
